#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：back 
@File    ：notify_rule.py
@IDE     ：PyCharm 
@Author  ：七分是你
@Date    ：2024/6/29 下午12:28 
@explain : 
"""
import json
from datetime import datetime

from app import dao
from app.utils.str_util import StringUtil


class NotifyRule(object):
    @classmethod
    def get_cache(cls):
        cache_str = dao.redis_dao.get('cache_notify_rule')
        if cache_str and StringUtil.isJsonString(cache_str):
            return json.loads(cache_str)
        else:
            data = dao.NotifyQueryDao.get_notify_rules()
            cache_list = {}
            for value in data:
                if value.utype not in cache_list:
                    cache_list[value.utype] = {}
                    # 现在可以安全地设置 cache_list[value.utype][value.alias] = value

                cache_list[value.utype][value.alias] = value.to_dict()
            print("get_cache===", cache_list)
            dao.redis_dao.set('cache_notify_rule', json.dumps(cache_list))
        return cache_list

    @classmethod
    def notify(cls, uid, utype, alias, replace_arr: dict = None, link_param: int = 0, url_params: str = '',
               other_params: dict = None):
        uid = uid if isinstance(uid, list) else [uid]
        rule_all = cls.get_cache()
        if utype not in rule_all:
            return
        rule_all = rule_all[utype]
        if alias not in rule_all:
            return
        rule_one = rule_all[alias]
        today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
        timestamp_today = int(today.timestamp())
        if rule_one['max_time_per_day'] > 0:
            where = {
                'uid': uid,
                'alias': alias,
                'addtime': timestamp_today,
            }
            notify_log = dao.NotifyQueryDao.find_notify_log(**where)
            for result in notify_log:
                if result.num >= rule_one['max_time_per_day']:
                    uid.remove(result.uid)
            if len(uid) == 0:
                return
            notify_log = []
            for value in uid:
                notify_log.append({'uid': value, 'alias': alias, 'addtime': timestamp_today})
            dao.NotifyOperateDao.insert_all(notify_log)
            message_to_arr = sms_to_arr = mail_to_arr = []
            if rule_one['open_message'] == 1:
                message_to_arr = uid
            if rule_one['open_sms'] == 1 or rule_one['open_email'] == 1:
                # 发送邮件或者短信功能接口，后面再接
                member_list = dao.MemberQueryDao.find_member_list(field_names=['uid', 'mobile', 'email'],
                                                                  **{'uid': uid})
                if not member_list:
                    return
                if 1 == len(uid) and other_params:
                    _next = True
                    if alias in ['job_audit_success', 'job_audit_fail', 'job_apply']:
                        if 'job_id' not in other_params or not other_params['job_id']:
                            _next = False
                        if _next:
                            job_id = other_params['job_id']
                            job_info = dao.JobQueryDao.find(**{'id': job_id})
                            if job_info and job_info.need_notice != 1:
                                member_list[0].mobile = ''
                                _next = False
                        if _next:
                            job_contact = dao.JobContactQueryDao.find(**{'jid': job_id})
                            if not job_contact:
                                _next = False
                        if _next:
                            if 0 == job_contact.use_company_contact:
                                member_list[0].mobile = job_contact.mobile
                            if 1 == job_contact.use_company_contact:
                                company_contact = dao.CompanyContactQueryDao.find(**{'comid': job_info.company_id})
                                if not company_contact:
                                    _next = False
                                if _next:
                                    member_list[0].mobile = company_contact.mobile
                for value in member_list:
                    if rule_one['open_sms'] == 1 and value.mobile:
                        sms_to_arr.append(value.mobile)
                    if rule_one['open_email'] == 1 and value.email:
                        mail_to_arr.append(value.email)
            content = cls.replace_content(rule_one['content'], replace_arr)
            if message_to_arr:
                message_to_arr = list(dict.fromkeys(message_to_arr))
                if isinstance(content, list):
                    for v in content:
                        dao.MessageOperateDao.send_message(message_to_arr, v, rule_one['type'], rule_one['inner_link'],
                                                           link_param, url_params)
                else:
                    dao.MessageOperateDao.send_message(message_to_arr, content, rule_one['type'],
                                                       rule_one['inner_link'], link_param, url_params)
            if sms_to_arr:
                sms_to_arr = list(dict.fromkeys(sms_to_arr))
                # 发送短信接口
                print(sms_to_arr)
            if mail_to_arr:
                mail_to_arr = list(dict.fromkeys(mail_to_arr))
                # 发送邮件接口
                print(mail_to_arr)

    @classmethod
    def replace_content(cls, content, replace_dict):
        if not isinstance(replace_dict, dict):
            raise TypeError("replace_dict must be a dictionary")

        # 如果replace_dict的value是列表，我们需要对列表中的每个项进行替换，并收集结果
        if any(isinstance(v, list) for v in replace_dict.values()):
            arr = []
            for key, value in replace_dict.items():
                if isinstance(value, list):
                    # 初始化contents为content的副本，避免在循环中修改原始内容
                    contents = content
                    for k, v in value:
                        contents = contents.replace('{' + k + '}', str(v))
                    arr.append(contents)
            return arr

        # 如果replace_dict的value不是列表，我们直接对content进行替换
        for key, value in replace_dict.items():
            content = content.replace('{' + key + '}', str(value))

        return content
